﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text.RegularExpressions;

namespace OPENXMLLib
{
    public static class RowExtention
    {
        public static Cell GetCell(this Row row, string cellReference, bool autoCreate = true)
        {
            if (row == null)
            {
                return null;
            }
            Regex regex = new Regex("[A-Za-z]+");
            Match match = regex.Match(cellReference);
            cellReference = string.Format("{0}{1}", match.Value, row.RowIndex);
            Cell cell = row.Elements<Cell>().Where(p => p.CellReference.Value == cellReference).SingleOrDefault();
            if (autoCreate)
            {
                if (cell == null)
                {
                    cell = new Cell();
                    cell.CellReference = cellReference;
                    CellValue cv = new CellValue();
                    cv.InnerXml = string.Empty;
                    cell.DataType = CellValues.String;
                    row.Append(cell);
                }
            }
            return cell;
        }

        public static SheetData GetSheetData(this Row row)
        {
            return (row.Parent as SheetData);
        }
    }
}
